<?php
class controller_KarmaController {
    private $view;
    private $args;

    public function setView(View $view) {
        $this->view = $view;
        return $this;
    }

    public function setArgs($args = null) {
        if(null != $args) {
            $this->args = $args;
        }
        return $this;
    }

    public function run() {

        if(empty($this->args['action'])) {
            $this->redir();
        } else {
            switch ($this->args['action']) {

                case 'vote':
                    $this->vote();
                    break;

                case 'update':
                    $this->update();
                    break;

                default:
                    $this->redir();
            }
        }
    }

    public function vote() {

        $t = 1500;
//1 - повышение кармы
//2 - понижение

        if(empty($_POST['vote'])) {
            $text = 'Ошибка, проголосуйте ещё раз!';
        } else {
            $mapper = new model_KarmaMapper();
            $post = model_ConfigMapper::validate($_POST);

            if ($mapper->validVote($t, $post)) {

                $mapper->vote($post);

                if(1 == $_POST['vote']) {
                    $mapper->upKarma($post);
                } else {
                    $mapper->downKarma($post);
                }

                $text = $mapper->find($post);

            } else {
                $text = 'Голосовать за одного юзера можно только раз в '. $t/60 .' минут';
            }
        }

        $this->view->message = $text;
        $this->view->setRenderTemplate("vote.phtml");
    }

    public function update() {

        $mapper = new model_KarmaMapper();
        $post = model_ConfigMapper::validate($_POST);

        $this->view->message = $mapper->update($post);
        $this->view->setRenderTemplate("vote.phtml");
    }

    public function redir() {

        $this->view->setRenderTemplate("redirect.phtml");
    }
}